<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>{{ $route.query.type == "add" ? '新建学习填报' : "编辑学习填报" }}</span>
        <el-button type="primary" :loading="buttonLoading" @click="goList">退出</el-button>
      </div>
    </template>

    <div class="add-form" v-loading="loading">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="140px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="学习时间" prop="studyDate">
          <el-date-picker
            v-model="ruleForm.studyDate"
            type="date"
            placeholder="请选择学习时间"
            value-format="YYYY-MM-DD"
            clearable
            :disabled-date="disabledDate"
          />
        </el-form-item>

        <el-form-item label="填报单位" prop="studyUnitName">
          <el-input v-model="ruleForm.studyUnitName" placeholder="请输入填报单位" disabled></el-input>
        </el-form-item>

        <el-form-item label="学习人次" prop="studyPersonNum">
          <el-input-number
            v-model="ruleForm.studyPersonNum"
            controls-position="right"
            style="width: 100%;"
            placeholder="请输入学习人次"
            :min="1"
          />
        </el-form-item>

        <el-form-item label="学习主题" prop="studySubject">
          <el-select v-model="ruleForm.studySubject" placeholder="请选择学习主题">
            <el-option v-for="(sItem, sIndex) in learnSubject" :key="sIndex" :label="sItem.name" :value="sItem.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="主持人" prop="studyHost">
          <el-input v-model="ruleForm.studyHost" placeholder="请输入主持人姓名"></el-input>
        </el-form-item>

        <el-form-item label="主讲人" prop="studySpeaker">
          <el-input v-model="ruleForm.studySpeaker" placeholder="请输入主讲人姓名"></el-input>
        </el-form-item>

        <el-form-item label="发言人" prop="studySpokesman">
          <el-input v-model="ruleForm.studySpokesman" placeholder="请输入发言人姓名"></el-input>
        </el-form-item>

        <el-form-item label="学习内容" prop="studyContent">
          <t-editor v-model="ruleForm.studyContent" @input="inputContent" style="width: 100%;"/>
        </el-form-item>

        <el-form-item label="学习形式" prop="studyWay">
          <el-select v-model="ruleForm.studyWay" placeholder="请选择学习形式">
            <el-option label="集体学习讨论" value="集体学习讨论" />
            <el-option label="专题辅导报告" value="专题辅导报告" />
            <el-option label="现场调研" value="现场调研" />
          </el-select>
        </el-form-item>

        <el-form-item label="参加人员" prop="studyPersons">
          <el-input v-model="ruleForm.studyPersons" placeholder="请输入参加人员"></el-input>
        </el-form-item>

        <el-form-item label="学习情况盖章附件" prop="studyFileName">
          <upload-file-result :fileList="fileList" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="uploadEvent">
            <el-icon>
              <UploadFilled />
            </el-icon>
            上传学习文件
          </el-button>
          <span style="margin-left: 10px;">请上传不超过20M的文件，格式：jpg/jpeg/png/mp4/doc/docx/xls/xlsx/ppt/pptx/pdf</span>
        </el-form-item>
        
        <el-form-item class="add-button">
          <el-button type="primary" :loading="buttonLoading" @click="submitForm(ruleFormRef)">
            {{ $route.query.type == "add" ? '新增' : "编辑" }}
          </el-button>
          <el-button :loading="buttonLoading" @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
export default { name: 'backendLearnFillingAdd' }
</script>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router'
import { UploadFilled } from '@element-plus/icons-vue'
import tEditor from "@/components/tinymceEditor/tEditor.vue"
import { ElMessage } from 'element-plus'
import { http } from '@/utils/http/index';
import { format } from '@/plugins/moment.js'
import { uploadFile } from '@/utils/file.js'
import { testFileType, testFileSize, isJsonString } from '@/utils/backend.js'
import { useAuthStore } from '@/stores/modules/auth.js';
import uploadFileResult from "@/components/backend/fileList.vue"

/* 路由 */
const route = useRouter()

/* 用户信息 */
const authStore = useAuthStore()

onMounted(() => {
  /* 如果是编辑，查询详情填充表单项 */
  if(route.currentRoute.value.query.id){
    getFillingDetail()
  }

  getLearnSubject()
  /* 如果是从学习主题列表跳转过来，默认选中此主题 */
  if(route.currentRoute.value.query.subjectId){
    ruleForm.value.studySubject = route.currentRoute.value.query.subjectId
  }
})

/* 详情数据加载动画 */
const loading = ref(false)

/* 查询详情 */
const getFillingDetail = () => {
  loading.value = true
  http.$GET("/TheoryStudyM/GetTheoryStudyFillingDetailById", { Id: route.currentRoute.value.query.id }).then(res => {
    loading.value = false
    if (res.isError) return
    if (!res.result) return

    /* 赋值 */
    Object.keys(ruleForm.value).forEach((key)=>{
      if(res.result[key] != null){
        ruleForm.value[key] = res.result[key];
      }
    })

    /* 处理学习日期 */
    ruleForm.value.studyDate = format(res.result.studyDate)

    /* 附件 */
    if(!isJsonString(res.result.studyFileName)){
      fileList.value = []
      ruleForm.value.studyFileName = ""
      return
    }
    if(res.result.studyFileName != ''){
      let fileName = JSON.parse(res.result.studyFileName)

      if(fileName.filePathArray){
        fileList.value = fileName.filePathArray
      }else{
        fileList.value = []
        ruleForm.value.studyFileName = ""
      }
    }
  }).catch(err => {
    loading.value = false
    ElMessage.warning("查询失败")
  })
}

/* 学习主题下拉列表请求 */
const learnSubject = ref([])
const subjectPageIndex = ref(1)
const subjectPageSize = ref(200)

const getLearnSubject = () => {
  let params = {
    pageIndex: subjectPageIndex.value,
    pageSize: subjectPageSize.value
  }
  http.$POST(`/TheoryStudyM/GetTheoryStudySubjectLocalInfoList`, params).then(res => {
    learnSubject.value = learnSubject.value.concat(res.result.dataLst)
    if(res.result.countAll > res.result.pageIndex * res.result.pageSize){
      subjectPageIndex.value = subjectPageIndex.value + 1
      getLearnSubject()
    }
  }).catch(err => {
    ElMessage.warning("查询失败")
  })
}

/* 日期禁选范围 */
const disabledDate = (time) => {
  return time.getTime() < new Date() - 24 * 60 * 60 * 1000
}

/* 新增、编辑表单 */
const ruleFormRef = ref(null)

/* 新增、编辑表单值 */
const ruleForm = ref({
  id: "",
  studyDate: "",
  studyUnit: authStore.userInfo.orgId ? authStore.userInfo.orgId : "",
  studyUnitName: authStore.userInfo.orgName ? authStore.userInfo.orgName : "",
  studyPersonNum: null,
  studySubject: "",
  studyHost: "",
  studySpeaker: "",
  studySpokesman: "",
  studyContent: "",
  studyWay: "",
  studyPersons: "",
  studyFileName: null,
})

/* 附件列表 */
const fileList = ref([])
/* 是否有上传附件 */
const isUploadFile = ref(false)

/* 校验附件规则 */
const checkFile = (rule, value, callback) => {
  if (ruleForm.value.studyFileName.length == 0) {
    callback(new Error('请上传附件'))
  } else {
    callback()
  }
}

/* 表单校验规则 */
const rules = reactive({
  studyUnitName: [
    { required: true, message: '无上级单位不允许填报', trigger: 'change' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  studyDate: [
    { required: true, message: '请选择学习时间', trigger: 'change' }
  ],
  studyPersonNum: [
    { required: true, message: '请输入学习人数', trigger: 'change' }
  ],
  studySubject: [
    { required: true, message: '请选择学习主题', trigger: 'change' },
  ],
  studyHost: [
    { required: true, message: '请输入主持人', trigger: 'change' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  studySpeaker: [
    { required: true, message: '请输入主讲人', trigger: 'change' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  studySpokesman: [
    { required: true, message: '请输入发言人', trigger: 'change' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  studyContent: [
    { required: true, message: '请输入学习内容', trigger: 'change' }
  ],
  studyWay: [
    { required: true, message: '请选择学习形式', trigger: 'change' }
  ],
  studyPersons: [
    { required: true, message: '请输入参加人员', trigger: 'change' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  /* studyFileName: [
    { required: true, validator: checkFile, message: '请上传附件', trigger: 'change' }
  ], */
})

/* 富文本内容变化 */
const inputContent = (newVal) => {
  if(newVal){
    ruleFormRef.value.clearValidate('studyContent')
  }
  ruleForm.value.studyContent = newVal
}

/* 点击上传文件 */
const uploadEvent = () => {
  /* 文件上传类型 */
  let fileType = ".jpg,.jpeg,.png,.JPG,.JPEG,.PNG,.mp4,.MP4,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.DOC,.DOCX,.XLS,.XLSX,.PPT,.PPTX,.PDF"

  uploadFile({ accept: fileType, multiple: true }).then(res => {
    /* 文件格式判断 */
    if(!testFileType(res, /^(jpg|jpeg|png|JPG|JPEG|PNG|mp4|MP4|doc|docx|xls|png|xlsx|ppt|pptx|pdf|DOC|DOCX|XLS|XLSX|PPT|PPTX|PDF)$/)){
      ruleForm.value.studyFileName = null
      fileList.value = []
      isUploadFile.value = false
      return 
    }

    /* 文件大小判断 */
    if(!testFileSize(res, 20*1024*1024)){
      ruleForm.value.studyFileName = null
      fileList.value = []
      isUploadFile.value = false
      return 
    }

    console.log(res, "文件上传成功")
    if(res){
      isUploadFile.value = true
      ruleForm.value.studyFileName = res
      /* 上传成功后清除校验 */
      ruleFormRef.value.clearValidate("studyFileName")
      /* 文件列表 */
      fileList.value = res
    }
  })
}

/* 提交新增或编辑时，按钮禁用 */
const buttonLoading = ref(false)

/* 提交新增、编辑 */
const submitForm = (formName) => {
  ruleFormRef.value.validate((valid, fields) => {
    if(valid) {
      buttonLoading.value = true

      /* 新增时不传id */
      if(route.currentRoute.value.query.type == 'add'){
        delete ruleForm.value.id
      }

      /* 未更新附件时不传值 */
      if(!isUploadFile.value) {
        delete ruleForm.value.studyFileName
      }

      /* 参数处理 */
      const formData = new FormData();

      for(let k in ruleForm.value){
        if(isUploadFile.value){
          if(k == 'studyFileName'){
            for(let j in ruleForm.value[k]){
              if(j < ruleForm.value[k].length){
                formData.append(k, ruleForm.value[k][j]);
              }
            }
          }else{
            formData.append(k, ruleForm.value[k]);
          }
        }else{
          formData.append(k, ruleForm.value[k]);
        }
      }

      if(authStore.auth_token){
        formData.append('authToken', authStore.auth_token)
      }

      http.$POST("/TheoryStudyM/AddOrUpdateTheoryStudyFilling", formData).then(res => {
        buttonLoading.value = false
        if (res.IsError) {
          ElMessage({
            type: 'warning',
            message: '操作失败',
          })
        }else{
          ElMessage({
            type: 'success',
            message: '操作成功',
          })
          route.push({
            path: "/backend/learn-filling"
          })
        }
      }).catch(err => {
        buttonLoading.value = false
        ElMessage({
          type: 'warning',
          message: '操作失败',
        })
      })
    }else{
      ElMessage({
        type: 'warning',
        message: '请先完成必填项',
      })
    }
  })
}

/* 重置表单 */
const resetForm = (formName) => {
  ruleFormRef.value.resetFields()
  fileList.value = []
  isUploadFile.value = false
}

/* 返回列表 */
const goList = () => {
  route.push({
    path: "/backend/learn-filling",
    query: route.currentRoute.value.query.currentPage ? { currentPage: route.currentRoute.value.query.currentPage } : {}
  })
}
</script>

<style lang='scss' scoped>
@import "@/assets/styles/backendElement.scss";
</style>